<?php

function rpc( $json_request ) {
    global $PARAPARA;

    $req_param = $json_request->param;

    if(!$req_param) {
        return new RPC_Error($json_request->operation, "PARAM", "No params");
    };

    $MAX_TEXT_LEN = 250;

    $text = $req_param->text;
    if( !is_string( $text ) || !strlen( $text ) || 
        ( strlen( $text ) > $MAX_TEXT_LEN ) )
        return new RPC_Error( $json_request->operation, "PARAM", "text empty or too long" );

    $account = $PARAPARA->fetch_account();


    #### check if anonymous
    if( ( $account == null) && 
        ( $PARAPARA->config_get('CHAT',  'ALLOW_ANONYMOUS') != 'true') ) {
        return new RPC_Error($json_request->operation, "AUTH", "Not authorized to post annonymously");
    }

    #### check ip blocks 
    if( $ipblock = $PARAPARA->is_ipblocked() ) {
        return new RPC_Error($json_request->operation, "BLOCKED", $ipblock->message );
    }

    $screen_name = $PARAPARA->get_screen_name();
    $user_id     = $PARAPARA->get_uid();
    $ip          = $PARAPARA->remote_addr;

    $dbl = $PARAPARA->dblayer;

    $status = $dbl->create_chat_message( $screen_name, $user_id, $text, $ip );

    if($status == 'ok') {
        $messages = $dbl->get_chat_messages( 0 );
        $chat     = new Chat( $messages );
    }


    $rpc_retval = array( 'status'      => $status, 
                         'html'        => $chat->as_html( null ), 
                         'shout_count' => $chat->shout_count,
                         'newest_id'   => $chat->newest_id
        );
    return new RPC_Response( $json_request->operation, $rpc_retval );

}

return rpc( $json_request );

?>